package ribbon.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 轮询策略，每台机器访问5次就轮询到下一个机器
 */
public class MyRule extends AbstractLoadBalancerRule {
    /**
     * total = 0，当total==5以后，我们指针才能往下走
     * index = 0，当前对外提供服务的服务器地址
     */
    private int total = 0;
    private int index = 0;

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();     //获取所有可用服务
                List<Server> allList = lb.getAllServers();          //获取所有服务列表
                int serverCount = allList.size();
                if (serverCount == 0 || upList.size() == 0) {
                    return null;
                }

                if(total < 5){
                    server = upList.get(index);
                    total++;
                }else{
                    total = 0;
                    index++;
                    if(index >= upList.size()){
                        index = 0;
                    }
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
